package com.vogue.supplymall.common.domain.jacksonutil;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * Created by Administrator on 2018-01-23.
 * 数据型序列化
 */
public class NumberSerializer extends com.fasterxml.jackson.databind.ser.std.NumberSerializer{

    private static ThreadLocal<Boolean> long2str= new ThreadLocal<Boolean>();//是否long型转为string
    private boolean ifl2s;

    public NumberSerializer(Class<? extends Number> rawType, boolean long2str) {
        super(rawType);
        ifl2s=long2str;
    }

    public NumberSerializer(Class<? extends Number> rawType) {
        super(rawType);
    }

    @Override
    public void serialize(Number value, JsonGenerator g, SerializerProvider provider) throws IOException {
        // should mostly come in as one of these two:
        if (value instanceof BigDecimal) {
            g.writeNumber((BigDecimal) value);
        } else if (value instanceof BigInteger) {
            boolean f=ifl2s;
            if(long2str.get() != null){
                f=long2str.get();
            }
            if(f){
                g.writeString(value.toString());
            }else{
                g.writeNumber((BigInteger) value);
            }
        } else if (value instanceof Long) {
            boolean f=ifl2s;
            if(long2str.get() != null){
                f=long2str.get();
            }
            if(f){
                g.writeString(value.toString());
            }else{
                g.writeNumber(value.longValue());
            }
        } else if (value instanceof Double) {
            g.writeNumber(value.doubleValue());
        } else if (value instanceof Float) {
            g.writeNumber(value.floatValue());
        } else if (value instanceof Integer || value instanceof Byte || value instanceof Short) {
            g.writeNumber(value.intValue()); // doesn't need to be cast to smaller numbers
        } else {
            // We'll have to use fallback "untyped" number write method
            g.writeNumber(value.toString());
        }
    }

    public void setLong2str(boolean f){
        long2str.set(f);
    }
}
